import React,{useState,useEffect} from 'react';
import {Form, Input, Select, DatePicker, Button, Space, Modal, Row, Col, InputNumber} from "antd";
import dayjs from 'dayjs'
import QuarterOfYear from 'dayjs/plugin/quarterOfYear';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import {setRAMOptions, setSubOptions} from "@/redux/modules/subModule/action";
import {editFormType,columnDataType} from './data'
import {connect} from "react-redux";
dayjs.extend(QuarterOfYear)
dayjs.extend(customParseFormat)

function EditForm(props) {
    let {modalShow,title,modalOk,modalCancel,data,subAllOptions,userOptions,componentDisabled} = props
    const dateFormat = 'YYYY-MM-DD'
    const [editForm] = Form.useForm();
    const [initValues, setInitValues] = useState<columnDataType>({
        subId:'',
        username:'',
        uid:'',
        phoneNum:'',
        email:'',
        subscripte_type:'',
        subType:'',
        bqMoney:0,
        subNum:0,
        startDate:new Date(),
        endDate:new Date(),
    });
    const [subType, setSubType] = useState(1);
    const [subRate, setSubRate] = useState('');
    useEffect(() => {
        let obj = {
            ...data,
            startDate: data.startDate  ? dayjs(data.startDate) : null,
            endDate: data.endDate  ? dayjs(data.endDate) : null
        }
        setInitValues(obj)
        editForm.setFieldsValue(obj);
    }, [data]);

    const username_change = (value: string) => {
        let curUser = userOptions.filter(item=>item.value === value)
        if(curUser.length>0){
            editForm.setFieldsValue({phoneNum:curUser[0].phoneNum?curUser[0].phoneNum:'',email:curUser[0].email,subNum:curUser[0].subNum})
        }
    }
    const subscripte_type_change = (value: string) => {
        setSubRate('0')
        let curSub = subAllOptions.filter(item=>item._id === value)
        if(curSub.length>0){
            let curSubType = subAllOptions.filter(item=>item.subType == curSub[0].subType)
            let subType = curSubType[0].subType
            let subRAM = curSubType[0].subRAM
            let subMoney = curSubType[0].subMoney
            if(curSubType.length>0){//计算开始结束时间
                setSubType(subType)
                let startDate = dayjs()
                let endDate = dayjs()
                switch (subType) {
                    case 1:
                        startDate = dayjs()
                        endDate = dayjs().add(1,'M')
                        editForm.setFieldsValue({
                            bqMoney:subMoney,
                            startDate:startDate,
                            endDate:endDate,
                            subType:subType,
                            subRAM:subRAM
                        })
                        break;
                    case 2:
                        startDate = dayjs()
                        endDate = dayjs().add(1,'Q')
                        editForm.setFieldsValue({
                            bqMoney:subMoney,
                            startDate:startDate,
                            endDate:endDate,
                            subType:subType,
                            subRAM:subRAM
                        })
                        break;
                    case 3:
                        startDate = dayjs()
                        endDate = dayjs().add(1,'y')
                        editForm.setFieldsValue({
                            bqMoney:subMoney,
                            startDate:startDate,
                            endDate:endDate,
                            subType:subType,
                            subRAM:subRAM
                        })
                        break;
                    default:
                        editForm.setFieldsValue({
                            bqMoney:subMoney,
                            startDate:startDate,
                            endDate:endDate,
                            subType:subType,
                            subRAM:subRAM
                        })
                }
            }else{
                setSubType(null)
                editForm.setFieldsValue({
                    bqMoney:subMoney,
                    subType:null,
                })
            }
        }
    }
    const onChangeStartDate = (val) => {
        let startDate = dayjs(val).format(dateFormat)
        if(editForm.getFieldValue('endDate')){
            let endDate = dayjs(editForm.getFieldValue('endDate')).format(dateFormat)
            if(dayjs(startDate).isAfter(dayjs(endDate))){
                editForm.setFieldsValue({endDate:null})
            }
        }
    }
    const onChangeEndDate = (val) => {
        let endDate = dayjs(val).format(dateFormat)
        if(editForm.getFieldValue('startDate')){
            let startDate = dayjs(editForm.getFieldValue('startDate')).format(dateFormat)
            if(dayjs(startDate).isAfter(dayjs(endDate))){
                editForm.setFieldsValue({startDate:null})
            }
        }
    }
    const modalSubmit = () => {
        editForm.validateFields().then((values) => {
            let endDate = dayjs(values.endDate).endOf('day')
            let startDate = dayjs(values.startDate).startOf('day')
            modalOk({
                ...values,
                endDate:endDate,
                startDate:startDate,
                subType:subType,
            })
        })
    }
    const cancel = () => {
        modalCancel()
        setTimeout(()=>{
            editForm.resetFields()
        },800)
    }
    const computerRate = (e) => {
       let targetVal = e.target.value
       let target_subscripte_type = editForm.getFieldValue('subscripte_type')
       let bqMoney = Number(editForm.getFieldValue('bqMoney'))
       let target_money:number = 0
       let target_rate:string = '0'
       let curData = subAllOptions.filter(item=>item.value === target_subscripte_type)
        if(curData.length>0){
            target_money = Number(curData[0].subMoney)
            target_rate = (((target_money - bqMoney) / target_money) * 100).toFixed(2);
            setSubRate(target_rate)
        }
    }
    return (
        <Modal
            open={modalShow}
            title={title}
            onOk={modalSubmit}
            onCancel={cancel}
            footer={(_, { OkBtn, CancelBtn }) => (
                <>
                    <CancelBtn />
                    <OkBtn />
                </>
            )}
        >
            <Form
                form={editForm}
                disabled={componentDisabled}
                labelCol={{ span: 6 }}
            >
                <div className="userArea">
                    <div className="title">人员信息</div>
                    <div className="con">
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item label="人 员：" name="uid" labelCol={{ span: 3 }} rules={[{ required: true,message:'请选择人员'}]}>
                                    <Select
                                        defaultValue="lucy"
                                        style={{ width: '100%' }}
                                        onChange={username_change}
                                        options={userOptions}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item label="手机号：" name="phoneNum">
                                    <Input disabled/>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="邮 箱：" name="email">
                                    <Input disabled/>
                                </Form.Item>
                            </Col>
                        </Row>
                    </div>
                </div>
                <div className="userArea">
                    <div className="title">订阅信息</div>
                    <div className="con">
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item label="订阅方式：" name="subscripte_type" labelCol={{ span: 3}} rules={[{ required: true,message:'请选择订阅方式'}]}>
                                    <Select
                                        defaultValue="lucy"
                                        style={{ width: '100%' }}
                                        onChange={subscripte_type_change}
                                        options={subAllOptions}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item label="订阅金额：" name="bqMoney" rules={[{ required: true,message:'请输入订阅金额'}]}>
                                    <InputNumber style={{ width: '100%' }} onBlur={computerRate}/>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="订阅次数：" name="subNum">
                                    <InputNumber style={{ width: '100%' }}/>
                                </Form.Item>

                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={12}>
                                <div className="rateArea">
                                    <span className="label">折扣：</span>
                                    <span className="num">
                                        {subRate}
                                        {subRate===''?'':'%'}
                                    </span>
                                </div>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="内存：" name="subRAM" rules={[{ required: true,message:'请输入内存'}]}>
                                    <InputNumber style={{ width: '100%' }} disabled/>
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item label="开始时间：" name="startDate" rules={[{ required: true,message:'请选择开始时间'}]}>
                                    <DatePicker style={{ width: '100%' }}
                                                onChange={onChangeStartDate}
                                                format={dateFormat}
                                                defaultPickerValue={dayjs(initValues.startDate||new Date())}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="结束时间：" name="endDate" rules={[{ required: true,message:'请选择结束时间'}]}>
                                    <DatePicker style={{ width: '100%' }}
                                                onChange={onChangeEndDate}
                                                format={dateFormat}
                                                defaultPickerValue={dayjs(initValues.endDate||new Date())}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                    </div>
                </div>
            </Form>
        </Modal>
    );
}


const mapStateToProps = (state:any)=> {
    return{
        subAllOptions:state.subData.subAllOptions,
        userOptions:state.subData.userOptions,
    }
}
export default connect(mapStateToProps)(EditForm);
